package net.ib.mtalk.ui.attachment.vcard;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import net.ib.mtalk.R;
import net.ib.mtalk.base.BaseListActivity;
import net.ib.mtalk.util.MTalkLogWriter;
import net.ib.mtalk.util.TimeAdapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * VCard의 정보를 보여주고 아이템을 선택해서 보낼수 있는 액티비티
 * 
 * @author happy2v
 *
 */
public class VCardListActivity extends BaseListActivity implements OnClickListener {
	
	public static final String INTENT_VCARD_CONTENT	="vcard_content";
	public static final String INTENT_VCARD_FILE_NAME = "vcard_file_name"; 
	 
	private ContactAccessor mContactAccessor;
	private ContactStruct mContactStruct;
	private Context mContext;
	private List<VCardListItemStruct> mItems;
	private int							itemCount				= 0;
	private ImageView 					sendBtn;
	
	private static final int PICK_CONTACT_REQUEST = 1;
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch(msg.what) {
			default:
				break;
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_vcard_list);
		
		mContext = this;
		
		sendBtn = (ImageView)findViewById(R.id.vcard_send_btn);
		sendBtn.setImageResource(R.drawable.send_off);
		sendBtn.setOnClickListener(this);
		sendBtn.setClickable(false);
		
		mContactStruct = new ContactStruct();
		
		mContactAccessor = ContactAccessor.getInstance();
		
		startActivityForResult(mContactAccessor.getPickContactIntent(), PICK_CONTACT_REQUEST);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data){
		if(requestCode == PICK_CONTACT_REQUEST && resultCode == RESULT_OK){
			loadContactInfo(data.getData());
		}else{
			finish();
		}
	}
	
	 private void loadContactInfo(Uri contactUri) {
        AsyncTask<Uri, Void, ContactStruct> task = new AsyncTask<Uri, Void, ContactStruct>() {
            @Override
            protected ContactStruct doInBackground(Uri... uris) {
            	return mContactAccessor.loadContact(getContentResolver(), uris[0]);
            }

            @Override
            protected void onPostExecute(ContactStruct result) {
                bindView(result);
            }
        };
        task.execute(contactUri);
    }
	
	// 리스트를 클릭하면 아이템을 선택한다.
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		if(mItems.get(position) != null){
			mItems.get(position).checked = !mItems.get(position).checked;
			if(mItems.get(position).checked){
				switch(mItems.get(position).type){
					case ContactStruct.KIND_EMAIL:
						mContactStruct.emailList.get(mItems.get(position).position).isPrimary = true;
						break;					
					case ContactStruct.KIND_IM:
						mContactStruct.imList.get(mItems.get(position).position).isPrimary = true;
						break;					
					case ContactStruct.KIND_NOTE:
						mContactStruct.noteList.get(mItems.get(position).position).isPrimary = true;
						break;					
					case ContactStruct.KIND_ORGANIZATION:
						mContactStruct.organizationList.get(mItems.get(position).position).isPrimary = true;
						break;					
					case ContactStruct.KIND_PHONE:
						mContactStruct.phoneList.get(mItems.get(position).position).isPrimary = true;
						break;					
					case ContactStruct.KIND_POSTAL:
						mContactStruct.postalList.get(mItems.get(position).position).isPrimary = true;
						break;					
					case ContactStruct.KIND_EVENT:
					case ContactStruct.KIND_GROUP_MEMBERSHIP:
					case ContactStruct.KIND_NAME:
					case ContactStruct.KIND_NICKNAME:
					case ContactStruct.KIND_PHOTO:
					case ContactStruct.KIND_RELATION:
					case ContactStruct.KIND_SIP_ADDRESS:
					case ContactStruct.KIND_WEBSITE:
					default:
						break;					
				}
				itemCount++;
			}else{
				switch(mItems.get(position).type){
					case ContactStruct.KIND_EMAIL:
						mContactStruct.emailList.get(mItems.get(position).position).isPrimary = false;
						break;					
					case ContactStruct.KIND_IM:
						mContactStruct.imList.get(mItems.get(position).position).isPrimary = false;
						break;					
					case ContactStruct.KIND_NOTE:
						mContactStruct.noteList.get(mItems.get(position).position).isPrimary = false;
						break;					
					case ContactStruct.KIND_ORGANIZATION:
						mContactStruct.organizationList.get(mItems.get(position).position).isPrimary = false;
						break;					
					case ContactStruct.KIND_PHONE:
						mContactStruct.phoneList.get(mItems.get(position).position).isPrimary = false;
						break;					
					case ContactStruct.KIND_POSTAL:
						mContactStruct.postalList.get(mItems.get(position).position).isPrimary = false;
						break;					
					case ContactStruct.KIND_EVENT:
					case ContactStruct.KIND_GROUP_MEMBERSHIP:
					case ContactStruct.KIND_NAME:
					case ContactStruct.KIND_NICKNAME:
					case ContactStruct.KIND_PHOTO:
					case ContactStruct.KIND_RELATION:
					case ContactStruct.KIND_SIP_ADDRESS:
					case ContactStruct.KIND_WEBSITE:
					default:
						break;					
				}
				itemCount--;
			}
			if(itemCount > 0){
				sendBtn.setImageResource(R.drawable.send_on);
				sendBtn.setClickable(true);
			}else{
				sendBtn.setImageResource(R.drawable.send_off);
				sendBtn.setClickable(false);
			}
			updateCheck(v.findViewById(R.id.vcard_checkbtn), mItems.get(position));
		}
	}
	
	/**
	 * 클릭 리스너
	 */
	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.vcard_send_btn){
			makeSelectedContact();
		}
	}
	
	/**
	 * ContactStruct 를 vCard 형식의 스트링으로 만든다.
	 */
	private void makeSelectedContact(){
		VCardComposer composer = new VCardComposer();
		
		String vCardString = null;
		
		try{
			vCardString = composer.createVCard(mContactStruct, VCardComposer.VERSION_VCARD30_INT);
		}catch(Exception e){
			MTalkLogWriter.e(e);
		}
		
		if(vCardString != null){
			// vCard 스트링을 파일로 만든다.
			String fileName = "";
			if(mContactStruct.fullName != null && !mContactStruct.fullName.equals("")){
				fileName = mContactStruct.fullName;
			}else if(mContactStruct.name != null && !mContactStruct.name.equals("")){
				fileName = mContactStruct.name;
			}else{
				fileName = "vCard";
			}
			submitResult(vCardString, fileName);
		}else{
			Toast.makeText(mContext, R.string.toast_vcard_make_fail, Toast.LENGTH_SHORT);
		}
	}
	
	/**
	 * 결과를 세팅하고 이 액티비티를 종료한다. 이 액티비티의 호출자에게는 결과의 주소가 담긴 인텐트를 반환한다.
	 * @param fileContnet 결과 파일의 주소
	 */
	private void submitResult(String fileContnet, String fileName) {
		Intent intent = new Intent();
		intent.putExtra(INTENT_VCARD_CONTENT, fileContnet);
		intent.putExtra(INTENT_VCARD_FILE_NAME, fileName);
		if (fileContnet == null) {
			setResult(RESULT_CANCELED, intent);
		} else {
			setResult(RESULT_OK, intent);
		}
		finish();
	}
	
	// 체크된 아이템을 화면에 표시해준다.
	public void updateCheck(View checkIcon, VCardListItemStruct item){
		if(item.checked){
			((ImageView)checkIcon).setImageResource(R.drawable.btn_check_on);
		}else{
			((ImageView)checkIcon).setImageResource(R.drawable.btn_check_on_disable);
		}
	}
	
	// 어댑터를 연결한다.
	private void bindView(ContactStruct contactInfo) {
		ImageView vCardProfileImg = (ImageView)findViewById(R.id.vcard_profile_icon);
		TextView vCardNameText = (TextView)findViewById(R.id.vcard_name_text);
		
		mContactStruct = contactInfo;
		
		// 기본 화면을 설정한다.
		// 사진 표시
        if(contactInfo.photoBytes != null){
        	Bitmap photoBmp = null;
		    ByteArrayInputStream byteIn = new ByteArrayInputStream(contactInfo.photoBytes);
		    photoBmp = BitmapFactory.decodeStream(byteIn);
		    vCardProfileImg.setImageBitmap(photoBmp);
        }
        
        // 이름 표시 // 있을때까지 찾아보고 그래도 없으면 기본값을 넣는다.
        if(contactInfo.fullName != null){
        	vCardNameText.setText(contactInfo.fullName);
        }else if(contactInfo.name != null){
        	vCardNameText.setText(contactInfo.name);
        }else{
        	vCardNameText.setText(mContext.getString(R.string.vcard_default_name));
        }
		
        // 뷰를 그려주기 위한 리스트를 만들자.
		mItems = new ArrayList<VCardListItemStruct>();		
		// 필요한 아이템 추가
		if(contactInfo.phoneList != null){
			for(int i = 0; contactInfo.phoneList.size() > i; i++){
				mItems.add(new VCardListItemStruct(ContactStruct.KIND_PHONE,
								mContext.getString(VCardConst.getPhoneTypeRes(contactInfo.phoneList.get(i).type)),
								contactInfo.phoneList.get(i).number, i));
			}
		}
		if(contactInfo.emailList != null){
			for(int i = 0; contactInfo.emailList.size() > i; i++){
				mItems.add(new VCardListItemStruct(ContactStruct.KIND_EMAIL,
								mContext.getString(VCardConst.getEmailTypeRes(contactInfo.emailList.get(i).type)),
								contactInfo.emailList.get(i).address, i));
			}
		}
		if(contactInfo.postalList != null){
			for(int i = 0; contactInfo.postalList.size() > i; i++){
				mItems.add(new VCardListItemStruct(ContactStruct.KIND_POSTAL,
								mContext.getString(VCardConst.getPostalTypeRes(contactInfo.postalList.get(i).type)),
								contactInfo.postalList.get(i).formattedAddress, i));
			}
		}
		if(contactInfo.imList != null){
			for(int i = 0; contactInfo.imList.size() > i; i++){
				mItems.add(new VCardListItemStruct(ContactStruct.KIND_IM,
								mContext.getString(VCardConst.getImProtocolRes(contactInfo.imList.get(i).protocol)),
								contactInfo.imList.get(i).data, i));
			}
		}
		if(contactInfo.organizationList != null){
			for(int i = 0; contactInfo.organizationList.size() > i; i++){
				mItems.add(new VCardListItemStruct(ContactStruct.KIND_ORGANIZATION,
								mContext.getString(VCardConst.getOrganizationTypeRes(contactInfo.organizationList.get(i).type)),
								contactInfo.organizationList.get(i).company, i));
			}
		}
		if(contactInfo.noteList != null){
			for(int i = 0; contactInfo.noteList.size() > i; i++){
				mItems.add(new VCardListItemStruct(ContactStruct.KIND_NOTE,
								mContext.getString(R.string.vcard_item_note),
								contactInfo.noteList.get(i).note, i));
			}
		}
		
		VCardListAdapter vcard_adapter = new VCardListAdapter(this, mItems);
		setListAdapter(vcard_adapter);
	}
}
